package com.valten;

import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ThreadTest2 {

    public static void main(String[] args) throws Exception {
        // 开始时间
        long start = System.currentTimeMillis();
        List<String> list = new ArrayList<>();

        for (int i = 1; i <= 2000000; i++) {
            list.add(i + "");
        }

        // 线程池数量
        int poolSize = (2 * Runtime.getRuntime().availableProcessors()) + 1;
        // 创建一个线程池
        ExecutorService exec = Executors.newFixedThreadPool(poolSize);
        // 定义一个任务集合
        List<Callable<Integer>> tasks = new ArrayList<>();
        Callable<Integer> task;
        List<String> cutList;

        int size = list.size();
        int batch = size % 100000 == 0 ? size / 100000 : size / 100000 + 1;
        for (int j = 0; j < batch; j++) {
            int end = (j + 1) * 100000;
            if (end > size) {
                end = size;
            }
            cutList = list.subList(j * 100000, end);

            // System.out.println("第" + (i + 1) + "组：" + cutList.toString());
            final List<String> listStr = cutList;
            task = () -> {
                System.out.println(Thread.currentThread().getName() + "线程：" + listStr);
                return listStr.size();
            };
            // 这里提交的任务容器列表和返回的Future列表存在顺序对应的关系
            tasks.add(task);
        }

        List<Future<Integer>> results = exec.invokeAll(tasks);

        for (Future<Integer> future : results) {
            System.out.println(future.get());
        }

        // 关闭线程池
        exec.shutdown();
        System.out.println("线程任务执行结束");
        System.err.println("执行任务消耗了 ：" + (System.currentTimeMillis() - start) + "毫秒");
    }
}
